package com.haibara.codesubmiteval.chain.redisRunnerChain;

import cn.hutool.json.JSONUtil;
import com.haibara.codesubmiteval.constant.RedisKeyConstant;
import com.haibara.codesubmiteval.model.entity.User;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 预热用户通过题目id集合
 *
 * @Author: mengyu
 * @Date: 2025/4/29
 */
@Order(2)
@Component
@Slf4j
public class AcceptedQuestionIdsInitHandler extends RedisInitHandler {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public void handleRedisInit(RedisInitContext context) {
        for (User user : context.getUsers()) {
            Set<Long> acceptedIdsSet = new HashSet<>(JSONUtil.toList(user.getAcceptedQuestionIds(), Long.class));
            Set<String> strIds = acceptedIdsSet.stream()
                    .map(Object::toString)
                    .collect(Collectors.toSet());
            if (!strIds.isEmpty()) {
                stringRedisTemplate.opsForSet().add(
                        RedisKeyConstant.getCompleteKey(
                                RedisKeyConstant.userAcceptedQuestionIdsSet,
                                user.getId().toString()
                        ),
                        strIds.toArray(new String[0])
                );
            }
        }
        log.info("RedisInit - AcceptedQuestionIds完成");
        if (next != null) next.handleRedisInit(context);
    }
}
